<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Library\Tools;
use App\Library\UpTools;
use App\Models\Admin\Configs;
use App\Models\Admin\Picture;
use App\Models\Articles;
use App\Models\video\CommonServer;
use Carbon\Carbon;
use Illuminate\Http\Request;

class SiteconfigController extends BaseController
{
    private $field = [
        "basic" => ["title" => null, "site_status" => 1, "seo_title" => null, "qy_redirect" => null, "shortcut" => 0,  "shortcut_name" => '',  "shortcut_url" => '', "avatar_status" => 0, "seo_ico" => "", "copyright" => ""],
        "sms" => ["sms_appid" => null, "sms_appkey" => null, "sms_sign" => null, "code_template" => null],
        "agentWxAppForm" => ["wxapplet_name" => '', "member_wechat_qr" => '', "member_wechat_appid" => '', "member_wechat_secret" => '', "qy_mch_id" => '', "qy_mch_key" => '', "member_apiclient_cert" => '', "member_apiclient_key" => '', "wx_mini_upload_key" => '', "wx_service_provider_ticket" => "", "member_wechat_icon_id" => ""],
        "qy" => ["company_id" => '', "qy_agentId" => "", "qy_agentSecret" => '', "qywxLogin" => 0, "qy_wxSecret" => '', "tongxl_secret" => '', "punch_secret" => '', "qy_pay_secret" => ''],
        "bonusLimit" => ["bonus_month_proportion" => null, "bonus_proportion" => null, "bonus_explain" => null, "bonus_alone" => null, "bonus_month_second" => null, "bonus_small" => null, "bonus_today_second" => null],
    ]; //填入数据库需要存储的表字段
    private $fieldMsg = [
        "logo" => "logo", "site_title" => "站点标题", "seo_title" => "网站seo的标题", "copyright" => "版权信息", "sms_id" => "短信id",
        "sms_secret" => "短信secret", "sms_sign" => "短信签名", "sms_code" => "验证码模板ID"
    ];
    public function __construct(Request $request){
        parent::__construct($request);
    }

    //配置列表
    public function getDataList(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $configModel = new Configs();
    	$data = $configModel->getConfigByID();
        if (isset($data['member_wechat_qr'])){
            $data['member_wechat_qr'] = $this->processingPictures($data['member_wechat_qr']);
        }
        if (isset($data['seo_ico'])){
            $data['seo_ico'] = $this->processingPictures($data['seo_ico']);
        }
        global $scf_data;
        if(empty($scf_data["host"])){
            $host = $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER['SERVER_NAME'];
        }else{
            $host = $scf_data["host"];
        }
        $returnData = [];
        foreach ($this->field as $k => $v){
            $returnData[$k]["id"] = $data["id"];
            if(strpos($host, "democrm.netbcloud.com") !== false && in_array($k, ["agentWxAppForm", 'sms', 'qy'])){
                foreach ($v as $field => $i){
                    $returnData[$k][$field] = "已隐藏";
                }
            }else{
                foreach ($v as $field => $i){
                    $returnData[$k][$field] = isset($data[$field]) ? $data[$field] : $i;
                }
            }
        }
        $res = file_get_contents("https://update.netbcloud.com/public/index.php/wxApp/getIp");
        $result = json_decode(trim($res, chr(239) . chr(187) . chr(191)), true);
        $returnData['agentWxAppForm']['uploadIp'] = $result['data']['ip'];
        if(!$returnData['agentWxAppForm']['member_wechat_qr']){
            $returnData['agentWxAppForm']['member_wechat_qr'] = $this->getQr($returnData['agentWxAppForm']['member_wechat_appid'], $returnData['agentWxAppForm']['member_wechat_secret'], false);
        }
        if (isset($returnData['agentWxAppForm']['member_wechat_icon_id'])){
            $returnData['agentWxAppForm']['member_wechat_icon_url'] = $this->processingPictures($returnData['agentWxAppForm']['member_wechat_icon_id']);
        }
        //用户协议加载
        $agreement = Articles::where('typeid',6)->where("mall_id", request()->mallData["id"])->first();
        if ($agreement){
            $agreement = json_decode(json_encode($agreement),true);
            $returnData["agreement"]['agreementTitle'] = $agreement['title'];
            $returnData["agreement"]['agreementContent'] = $agreement['content'];
        }else{
            $returnData["agreement"]['agreementTitle'] = '';
            $returnData["agreement"]['agreementContent'] = '';
        }
        $returnData["agreement"]["id"] = $data["id"];
        //隐私协议
        $privacy = Articles::where('typeid',7)->where("mall_id", request()->mallData["id"])->first();
        if ($privacy){
            $privacy = json_decode(json_encode($privacy),true);
            $returnData["privacy"]['privacyTitle'] = $privacy['title'];
            $returnData["privacy"]['privacyContent'] = $privacy['content'];
        }else{
            $returnData["privacy"]['privacyTitle'] = '';
            $returnData["privacy"]['privacyContent'] = '';
        }
        $returnData["privacy"]["id"] = $data["id"];
        $this->returnData["data"] = $returnData;
        return $this->return_result($this->returnData);
    }

    //更新系统配置
    public function update(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if ($request->post('type') == "agreement") {  //用户协议修改
            $res = Articles::where('typeid',6)->where("mall_id", request()->mallData["id"])->first();
            $where['title'] = $request->post('agreementTitle','');
            $where['content'] = $request->post('agreementContent','');
            if ($res){
                $where['updated_at'] = Carbon::now()->toDateTimeString();
                $update_res = Articles::where('typeid',6)->where("mall_id", request()->mallData["id"])->update($where);
            }else{
                $where['typeid'] = 6;
                $where['created_at'] = Carbon::now()->toDateTimeString();
                $where["mall_id"] = $request->mallData["id"];
                $update_res = Articles::insert($where);
            }
            if (!$update_res){
                $this->returnData['code'] = 1;
                $this->returnData['msg'] = '修改失败';
                return $this->return_result($this->returnData);
            }else{
                return $this->return_result($this->returnData);
            }
        }else if ($request->post('type') == "privacy") {  //隐私协议修改
            $res = Articles::where('typeid',7)->where("mall_id", request()->mallData["id"])->first();
            $where['title'] = $request->post('privacyTitle','');
            $where['content'] = $request->post('privacyContent','');
            if ($res){
                $where['updated_at'] = Carbon::now()->toDateTimeString();
                $update_res = Articles::where('typeid',7)->where("mall_id", request()->mallData["id"])->update($where);
            }else{
                $where['typeid'] = 7;
                $where['created_at'] = Carbon::now()->toDateTimeString();
                $where["mall_id"] = $request->mallData["id"];
                $update_res = Articles::insert($where);
            }
            if (!$update_res){
                $this->returnData['code'] = 1;
                $this->returnData['msg'] = '修改失败';
                return $this->return_result($this->returnData);
            }else{
                return $this->return_result($this->returnData);
            }
        }elseif(!isset($this->field[$request->post('type')])){
            $this->returnData = ErrorCode::$admin_enum['not_exist'];
            $this->returnData['msg'] = 'type参数错误';
            return $this->return_result($this->returnData);
        }else{
            $data = [];
            foreach ($this->field[$request->post('type')] as $k => $v) {
                $data[$k] = $request->post($k, $v);
            }
            if(isset($data['member_wechat_appid'])) {
                $data['member_wechat_qr'] = $this->getQr($data['member_wechat_appid'], $data['member_wechat_secret']);
            }
            global $scf_data;
            if(empty($scf_data["host"])){
                $host = $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER['SERVER_NAME'];
            }else{
                $host = $scf_data["host"];
            }
            if(strpos($host, "democrm.netbcloud.com") === false){
                if(isset($data["company_id"])) { // 企业微信回调地址
                    $data["qy_redirect"] = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid={$data["company_id"]}&agentid={$data["qy_agentId"]}&redirect_uri={$host}/admin/qy/login&state=STATE";
                }
                $configModel = new Configs();
                $res = $configModel->configUpdate($data);
                if(!$res){
                    $this->returnData = ErrorCode::$admin_enum['not_exist'];
                    $this->returnData['msg'] = '更新失败';
                    return $this->return_result($this->returnData);
                }
            }
            $this->returnData['msg'] = "更新成功";
        }
        return $this->return_result($this->returnData);
    }

    private function getQr($appId, $appSecret, $update = true){
        $response = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}");
        $result = json_decode($response, true);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            if($update)
                throw new \Exception($result["errmsg"]);
            return "";
        } else {
            $access_token = $result['access_token'];
        }
        $data = ['scene' => "0"];
        $result = Tools::curl("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}", json_encode($data, JSON_UNESCAPED_SLASHES));
        $response = json_decode($result, true);
        if (empty($response['errcode'])) {
            $file = "attachment/wxapp/crm/{$appId}.png";
            global $scf_data;
            if(!empty($scf_data["IS_SCF"])){ // 云开发
                $object = new Picture();
                $result = $object->uploadImg($file, $result);
                return $result['ObjectURL'];
            }else{
                if(!file_exists(base_path() . "/public/"  . $file)){
                    UpTools::mkdir(dirname(base_path() . "/public/" . $file));
                }
                file_put_contents(base_path() . "/public/"  . $file, $result);
                return CommonServer::getUrl($file);
            }
        } else {
            if($update)
                throw new \Exception($response["errmsg"]);
            return '';
        }
    }
}
